﻿using TFramework.ECS.Component;
using TFramework.ECS.Entity;
using TFramework.ECS.Group;
using TFramework.Extensions;
using UnityEngine;

namespace TFramework.ECS.System
{
    public class ViewSystem : ISetupSystem, ITeardownSystem
    {
        public IGroup Group => new Group.Group(typeof(ViewComponent));

        public void Setup(IEntity entity)
        {
            var viewComponent = entity.GetComponent<ViewComponent>();
            if (viewComponent.View != null) { return; }
            OnViewCreated(entity, viewComponent);
        }

        public void Teardown(IEntity entity)
        {
            var viewComponent = entity.GetComponent<ViewComponent>();
            if (viewComponent.View != null) { return; }
            OnViewRemoved(entity, viewComponent);
        }

        protected virtual void OnViewCreated(IEntity entity, ViewComponent viewComponent)
        {
            viewComponent.View = Object.Instantiate(Resources.Load<GameObject>(viewComponent.Name));
        }

        protected virtual void OnViewRemoved(IEntity entity, ViewComponent viewComponent)
        {
            GameObject gameobject = viewComponent.View as GameObject;
            Object.Destroy(gameobject);
        }
    }
}